﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text.Json;
using TK.Common.AspNetCore;
using TK.Common.Json;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// ApiExtension
    /// </summary>
    public static class ApiExtension
    {
        /// <summary>
        /// mvc 相关服务封装
        /// </summary>
        public static IServiceCollection AddTKMvc(this IServiceCollection services)
        {
            services.AddMvc(option =>
            {

            })
            .ConfigureApiBehaviorOptions(option =>
            {
                option.SuppressConsumesConstraintForFormFileParameters= true;
                option.InvalidModelStateResponseFactory = actionContext =>
                {
                    //获取验证失败的模型字段 
                    var errors = actionContext.ModelState
                        .Where(e => e.Value.Errors.Count > 0)
                        .Select(e => e.Value.Errors.First().ErrorMessage)
                        .ToList();
                    return new BadRequestObjectResult(UnaryResult.Fail(string.Join("|", errors)));
                };
            })
            .AddJsonOptions(options =>
            {
                //数字序列成字符串
                options.JsonSerializerOptions.Converters.Add(new NumberConverter());
                options.JsonSerializerOptions.Converters.Add(new StringNullConverter());
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
            });
            services.AddCors(options =>
            {
                
            });
            //路由url小写
            services.AddRouting(options => options.LowercaseUrls = true);

            return services;
        }
    }
}
